<template>
  <div class="bg-settings">
    <el-form
      :model="shopDataForm"
      ref="shopDataForm"
      :rules="rules"
      label-width="200px"
      class="demo-ruleForm"
      status-icon>
      <!--店铺名称-->
      <el-form-item label="店铺名称：" prop="shop_name">
        <el-input v-model="shopDataForm.shop_name" @change="() => { shopDataForm.shop_name = shopDataForm.shop_name.trim() }" maxlength="15" style="width: 200px;" auto-complete="off"></el-input>
      </el-form-item>
      <!--身份证号-->
      <el-form-item label="身份证号：" prop="legal_id">
        <span>{{ shopDataForm.legal_id }}</span>
      </el-form-item>
      <!--店铺地址-->
      <el-form-item label="店铺地址：" prop="shop_region">
        <en-region-picker :api="MixinRegionApi" :default="areas" @changed="(object) => { shopDataForm.shop_region = object.last_id }"></en-region-picker>
      </el-form-item>
      <template v-if="isO2O">
        <!--地图定位-->
        <el-form-item label="地图定位：" prop="latitude">
          <div class="addr">{{ location_add }}</div>
          <span class="addr-tip">请在地图中确认地址信息</span>
          <div id="container" style="width:600px; height:450px">
            <el-input id="input" v-model="addressKeyword" placeholder="请搜索地址" clearable style="width:240px;z-index: 999;margin: 10px;">
              <el-button slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </div>
        </el-form-item>
        <!--详细地址-->
        <el-form-item label="详细地址：" prop="shop_add">
          <el-input v-model="shopDataForm.shop_add" @change="() => { shopDataForm.shop_add = shopDataForm.shop_add.trim() }"  style="width: 350px;" auto-complete="off"></el-input>
        </el-form-item>
        <!--配送范围-->
        <el-form-item label="配送范围：" prop="delivery_scope">
          <el-input v-model="shopDataForm.delivery_scope" style="width: 200px;" auto-complete="off"></el-input>
          <span>km</span>
        </el-form-item>
        <!--营业时间-->
        <el-form-item label="营业时间：" prop="business_hours" class="make">
          <el-radio-group v-model="shopDataForm.business_hours.timeRangeType">
            <el-radio label="ALL_DAY">全天</el-radio>
            <el-radio label="CUSTOM">自定义</el-radio>
          </el-radio-group>
          <div style="margin-left: 24px">
            <el-radio-group v-if="shopDataForm.business_hours.timeRangeType === 'CUSTOM'" v-model="shopDataForm.business_hours.editionTimeRangeType">
              <el-radio label="EVERYDAY">每天重复</el-radio>
              <el-radio label="WEEKLY">每周重复</el-radio>
            </el-radio-group>
            <div class="time-range-list" v-if="shopDataForm.business_hours.timeRangeType === 'CUSTOM' && shopDataForm.business_hours.editionTimeRangeType === 'EVERYDAY'">
              <div class="time-range-item" v-for="(time, index) in timeBucketDayRepeat" :key="index">
                <el-time-picker
                  placeholder="开始时间"
                  v-model="time.startTime"
                  :editable="false"
                  :clearable="false"
                  value-format="HH:mm"
                  format="HH:mm"
                  :picker-options="{selectableRange: '00:00:00 - 23:59:59'}">
                </el-time-picker>
                <span style="margin: 0 10px;">至</span>
                <el-time-picker
                  placeholder="结束时间"
                  v-model="time.endTime"
                  :editable="false"
                  :clearable="false"
                  value-format="HH:mm"
                  format="HH:mm"
                  :picker-options="{selectableRange: '00:00:00 - 23:59:59'}">
                </el-time-picker>
                <span class="del-btn btn" @click="handleDelTime(2, index, '')">删除</span>
              </div>
              <span class="add-btn btn" v-if="timeBucketDayRepeat && timeBucketDayRepeat.length < 3" @click="handleAddTime(2)">添加时间</span>
            </div>
            <div class="day-list" v-if="shopDataForm.business_hours.editionTimeRangeType === 'WEEKLY'">
              <div class="time-range-content" v-if="timeBucketWeekRepeat">
                <div class="time-range-list" v-for="(week, weekIndex) in timeBucketWeekRepeat" :key="weekIndex">
                  <div class="week-range-item">
                    <span class="add-btn">{{ week.week }}</span>
                    <span class="btn" @click="handleDelTime(3, '', weekIndex)">删除</span>
                  </div>
                  <div class="time-range-item" v-for="(time, timeIndex) in week.weekTime" :key="timeIndex">
                    <el-time-picker
                      placeholder="开始时间"
                      v-model="time.startTime"
                      :editable="false"
                      :clearable="false"
                      value-format="HH:mm"
                      format="HH:mm"
                      :picker-options="{selectableRange: '00:00:00 - 23:59:59'}">
                    </el-time-picker>
                    <span style="margin: 0 10px;">至</span>
                    <el-time-picker
                      placeholder="结束时间"
                      v-model="time.endTime"
                      :editable="false"
                      :clearable="false"
                      value-format="HH:mm"
                      format="HH:mm"
                      :picker-options="{selectableRange: '00:00:00 - 23:59:59'}">
                    </el-time-picker>
                    <span class="del-btn btn" @click="handleDelTime(3, timeIndex, weekIndex)">删除</span>
                  </div>
                  <span class="add-btn btn" v-if="week.weekTime && week.weekTime.length < 3" @click="handleAddTime(3, weekIndex)">添加时间</span>
                </div>
              </div>
              <div class="day-picker">
                <span class="add-btn btn" @click="showWeek = true">添加星期</span>
                <div class="popover-content" v-if="showWeek">
                  <div class="day-picker-list">
                    <el-checkbox-group v-model="week" @change="(value) => { week = value}">
                      <el-checkbox style="display: block;" v-for="week in weekList" :label="week" :key="week">{{ week }}</el-checkbox>
                    </el-checkbox-group>
                    <div class="day-picker-action">
                      <el-button @click="handleConfirm">确定</el-button>
                      <el-button @click="showWeek = false">取消</el-button>
                    </div>
                  </div>
                  <i class="arrow"></i>
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
      </template>
      <!--详细地址-->
      <el-form-item label="详细地址：" prop="shop_add" v-if="!isO2O">
        <el-input v-model="shopDataForm.shop_add" @change="() => { shopDataForm.shop_add = shopDataForm.shop_add.trim() }"  style="width: 200px;" auto-complete="off"></el-input>
      </el-form-item>
      <!--联系电话-->
      <el-form-item label="联系电话：" prop="link_phone">
        <el-input v-model="shopDataForm.link_phone" style="width: 200px;" maxLength="11"></el-input>
      </el-form-item>
      <!--QQ-->
      <el-form-item label="QQ：" prop="shop_qq" v-if="!MixinIsIM">
        <el-input v-model="shopDataForm.shop_qq" style="width: 200px;" placeholder="请设置店铺的客服QQ"></el-input>
        <span class="QQ-tip">（设置店铺的客服QQ）</span>
      </el-form-item>
      <!--店铺简介-->
      <el-form-item label="店铺简介：" prop="shop_desc">
        <UE ref="UE" :defaultMsg="shopDataForm.shop_desc" style="width: 80%;"></UE>
      </el-form-item>
      <!--店铺logo-->
      <el-form-item label="店铺logo：" prop="shop_logo">
        <el-upload
          class="upload-demo"
          key="shop_logo"
          :action="`${MixinUploadApi}?scene=shop`"
          :headers="MixinAccessToken"
          :on-success="uploadSuccessLogo"
          :on-remove="delGiftImg"
          :before-upload="handleImagesUrlBefore"
          :file-list="fileList_logo"
          ref="fileList_logo"
          list-type="picture">
          <el-button size="small" type="primary">
            上传<i class="el-icon-upload el-icon--right"></i>
          </el-button>
          <div slot="tip" class="el-upload__tip">
            此处为您的店铺logo，将显示在店铺Logo栏里。 （限制上传正方形的图片！）
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSaveShopData('shopDataForm')" :loading="saveLoading">保存修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import * as API_Shop from '@/api/shop'
  import * as API_O2O from '@/api/o2o'
  import { UE } from '@/components'
  import { RegExp } from '~/ui-utils'
  export default {
    name: 'shopSetting',
    components: {
      [UE.name]: UE
    },
    data() {
      const validPhone = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入联系人电话'))
        } else if (!RegExp.mobile.test(value)) {
          callback(new Error('请输入正确的11位手机号码'))
        } else {
          callback()
        }
      }
      const validQQ = (rule, value, callback) => {
        if (value && !/^[0-9]\d*$/g.test(value)) {
          callback(new Error('请输入0-9之间的整数'))
        } else {
          callback()
        }
      }
      const validScope = (rule, value, callback) => {
        if (!value && value !== 0) {
          callback(new Error('配送范围不能为空'))
        } else if (!RegExp.money.test(value)) {
          callback(new Error('请输入正整数或者两位小数'))
        } else if (parseFloat(value) > 99999999) {
          callback(new Error('配送范围设置超过上限值'))
        } else {
          callback()
        }
      }
      const validHours = (rule, value, callback) => {
        if (!value.timeBucket || value.timeBucket.length === 0) {
          callback(new Error('至少配置一个时间段'))
        } else {
          callback()
        }
      }
      return {
        location_add: '',
        /** 地址搜索关键字 */
        addressKeyword: '',
        /** 搜索结果 */
        searchResule: [],
        /** 是否显示搜素结果 */
        showSearchResule: false,
        searchService: [],
        marker: [],
        map: [],
        /** 营业时间 */
        week: [],
        weekList: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
        showWeek: false,
        /** 全天 */
        timeBucketDay: {
          startTime: '00:00',
          endTime: '23:59'
        },
        /** 每天重复 */
        timeBucketDayRepeat: [],
        /** 每周重复 */
        timeBucketWeekRepeat: [],
        /** 店铺信息*/
        shopDataForm: {
          /** 坐标 */
          latitude: 0,
          longitude: 0,

          /** 配送范围 */
          delivery_scope: '',

          /** 营业时间段 */
          business_hours: '',

          /** 店铺ID */
          shop_id: 0,

          /** 店铺名称 */
          shop_name: '',

          /** 身份证号*/
          legal_id: '',

          /** 店铺地址id */
          shop_region: '',

          /** 详细地址*/
          shop_add: '',

          /** 联系电话*/
          link_phone: '',

          /** QQ*/
          shop_qq: '',

          /** 店铺简介*/
          shop_desc: '',

          /** 店铺logo*/
          shop_logo: ''
        },

        /** 地区信息*/
        areas: [],

        /** 店铺logo图片存*/
        fileList_logo: [],

        /** 店铺banner图片存*/
        fileList_banner: [],

        /** 校验规则 校验必填 */
        rules: {
          /** 店铺名称 */
          shop_name: [
            { required: true, message: '请填写店铺名称', trigger: 'blur' },
            { whitespace: true, message: '店铺名称不可为纯空格', trigger: 'blur' },
            { max: 15, message: '店铺名称长度最多15个字符', trigger: 'blur' }
          ],

          /** 店铺地址 */
          shop_region: [
            { required: true, message: '请填写店铺地址', trigger: 'blur' }
          ],

          /** 地图定位 */
          latitude: [
            { required: true, message: '请选择地图定位', trigger: 'blur' }
          ],

          /** 详细地址 */
          shop_add: [
            { required: true, message: '请填写详细地址', trigger: 'blur' },
            { whitespace: true, message: '详细地址不可为纯空格', trigger: 'blur' },
            { max: 50, message: '详细地址长度最多50个字符', trigger: 'blur' }
          ],

          /** 配送范围 */
          delivery_scope: [
            { required: true, message: '请填写配送范围', trigger: 'blur' },
            { validator: validScope, trigger: 'blur' }
          ],

          /** 营业时间 */
          business_hours: [
            { required: true, message: '请选择营业时间', trigger: 'blur' },
            { validator: validHours, trigger: 'blur' }
          ],

          /** 联系人电话 */
          link_phone: [
            { required: true, message: '请填写联系人电话', trigger: 'blur' },
            { validator: validPhone, trigger: 'blur' }
          ],

          /** 店铺qq */
          shop_qq: [
            { required: false, trigger: 'change', validator: validQQ },
            { max: 20, message: '店铺QQ长度最多20个字符', trigger: 'change' }
          ]
        },
        // 保存按钮的loading
        saveLoading: false,
        // 防抖定时器
        timer: null
      }
    },
    mounted() {
      this.GET_ShopGradeData()
    },
    methods: {
      init() {
        let that = this
        let map = new AMap.Map('container', {
          zoom: 14,
          resizeEnable: true
        })
        /** 比例尺 */
        let scale = new AMap.Scale({
          visible: false
        })
        map.addControl(scale)
        scale.show()
        /** 搜索关键字 */
        let autoOptions = { input: 'input' }
        let auto = new AMap.Autocomplete(autoOptions)
        AMap.event.addListener(auto, 'select', function(event) {
          that.addMarker(event.poi.location)
        })
        /** 地图点击事件 */
        map.on('click', function(event) {
          that.addMarker(event.lnglat)
        })
        that.map = map
        /** 坐标地址存在时添加标注 */
        if (this.shopDataForm.latitude && this.shopDataForm.longitude) {
          const lnglat = new AMap.LngLat(this.shopDataForm.longitude, this.shopDataForm.latitude)
          that.addMarker(lnglat)
        }
      },

      /** 添加标注 */
      addMarker(lnglat) {
        let that = this
        that.map.clearMap()
        let marker = new AMap.Marker({
          icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_bs.png',
          position: lnglat,
          offset: new AMap.Pixel(-13, -30)
        })
        marker.setMap(that.map)
        that.map.setCenter(lnglat)
        let geocoder = new AMap.Geocoder({})
        let infoWindow = new AMap.InfoWindow({ offset: new AMap.Pixel(-3, -30) })
        geocoder.getAddress(lnglat, function(status, result) {
          if (status === 'complete' && result.regeocode) {
            infoWindow.setContent(result.regeocode.formattedAddress)
            infoWindow.open(that.map, that.marker.getPosition())
            that.location_add = result.regeocode.formattedAddress
            that.shopDataForm.shop_add = result.regeocode.formattedAddress
          } else {
            console.log('根据经纬度查询地址失败')
          }
        })
        that.marker = marker
        that.shopDataForm.latitude = lnglat.lat
        that.shopDataForm.longitude = lnglat.lng
      },

      /** 获取店铺信息 */
      GET_ShopGradeData() {
        if (this.isO2O) {
          API_O2O.getShopData().then(response => {
            let { business_hours } = response
            if (business_hours) {
              business_hours = JSON.parse(response.business_hours)
              if (business_hours.timeRangeType === 'CUSTOM') {
                if (business_hours.editionTimeRangeType === 'EVERYDAY') {
                  this.timeBucketDayRepeat = business_hours.timeBucket
                } else {
                  this.timeBucketWeekRepeat = business_hours.timeBucket
                }
              }
            } else {
              business_hours = {
                timeRangeType: 'ALL_DAY',
                timeBucket: this.timeBucketDay
              }
            }
            this.shopDataForm = { ...response }
            this.shopDataForm.business_hours = business_hours
            this.shopDataForm.shop_logo && (this.fileList_logo = [{ url: this.shopDataForm.shop_logo }])
            this.areas = [this.shopDataForm.shop_province_id, this.shopDataForm.shop_city_id,
              this.shopDataForm.shop_county_id || -1, this.shopDataForm.shop_town_id || -1]
            this.init()
            this.saveLoading = false
          })
        } else {
          API_Shop.getShopData().then(response => {
            this.shopDataForm = { ...response }
            this.shopDataForm.shop_logo && (this.fileList_logo = [{ url: this.shopDataForm.shop_logo }])
            this.areas = [this.shopDataForm.shop_province_id, this.shopDataForm.shop_city_id,
              this.shopDataForm.shop_county_id || -1, this.shopDataForm.shop_town_id || -1]
            console.log(response)
            this.saveLoading = false
          })
        }
      },

      /** 保存店铺设置*/
      handleSaveShopData(formName) {
        if (this.isO2O) {
          if (this.shopDataForm.business_hours.timeRangeType === 'ALL_DAY') {
            this.shopDataForm.business_hours.timeBucket = [{ ...this.timeBucketDay }]
          } else {
            if (this.shopDataForm.business_hours.editionTimeRangeType === 'EVERYDAY') {
              this.shopDataForm.business_hours.timeBucket = this.timeBucketDayRepeat
            } else {
              this.shopDataForm.business_hours.timeBucket = this.timeBucketWeekRepeat
            }
          }
        }
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.shopDataForm.shop_desc = this.$refs['UE'].getUEContent()
          this.$refs[formName].validate((valid) => {
            if (valid) {
              this.saveLoading = true
              if (this.isO2O) {
                const _params = {
                  latitude: this.shopDataForm.latitude,

                  longitude: this.shopDataForm.longitude,

                  shop_add: this.shopDataForm.shop_add,

                  shop_name: this.shopDataForm.shop_name,

                  link_phone: this.shopDataForm.link_phone,

                  shop_logo: this.shopDataForm.shop_logo,

                  shop_desc: this.shopDataForm.shop_desc || '',

                  shop_qq: this.shopDataForm.shop_qq,

                  shop_region: this.shopDataForm.shop_region,

                  delivery_scope: this.shopDataForm.delivery_scope || '',

                  business_hours: this.shopDataForm.business_hours
                }
                _params.business_hours = JSON.stringify(_params.business_hours)
                API_O2O.saveShopSettings(_params).then(() => {
                  this.$message.success('保存店铺设置成功')
                  // this.GET_ShopGradeData()
                  this.saveLoading = false
                  this.$store.dispatch('getShopInfoAction')
                })
              } else {
                const _params = {
                  shop_add: this.shopDataForm.shop_add,

                  shop_name: this.shopDataForm.shop_name,

                  link_phone: this.shopDataForm.link_phone,

                  shop_logo: this.shopDataForm.shop_logo,

                  shop_desc: this.shopDataForm.shop_desc || '',

                  shop_qq: this.shopDataForm.shop_qq,

                  shop_region: this.shopDataForm.shop_region
                }
                API_Shop.saveShopSettings(_params).then(() => {
                  this.$message.success('保存店铺设置成功')
                  // this.GET_ShopGradeData()
                  this.saveLoading = false
                  this.$store.dispatch('getShopInfoAction')
                })
              }
            }
          })
        }, 500)
      },

      /** 添加时间段 */
      handleAddTime(timeRangeType, weekIndex) {
        const params = {
          startTime: '',
          endTime: ''
        }
        if (timeRangeType === 2) {
          this.timeBucketDayRepeat.push(params)
        } else {
          this.timeBucketWeekRepeat[weekIndex].weekTime.push(params)
        }
      },

      /** 删除时间段 */
      handleDelTime(timeRangeType, timeIndex, weekIndex) {
        if (timeRangeType === 2) {
          this.timeBucketDayRepeat.splice(timeIndex, 1)
        } else {
          if (timeIndex) {
            this.timeBucketWeekRepeat[weekIndex].weekTime.splice(timeIndex, 1)
          } else {
            this.timeBucketWeekRepeat.splice(weekIndex, 1)
          }
        }
      },

      /** 添加星期 */
      handleConfirm() {
        this.showWeek = false
        const week = this.week.join('、')
        const weekTime = {
          startTime: '',
          endTime: ''
        }
        const params = {
          week,
          weekTime: [{ ...weekTime }]
        }
        this.timeBucketWeekRepeat.push(params)
      },

      /** 图片上传之前的校验 */
      handleImagesUrlBefore(file) {
        const isImage = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'
        if (!isImage) {
          this.$message.error('上传头像图片只能是 JPG、JPEG或PNG格式!')
          return isImage
        }
        return new Promise((resolve, reject) => {
          let reader = new FileReader()
          reader.onload = (event) => {
            let image = new Image()
            image.onload = () => {
              let width = image.width
              let height = image.height
              if (width !== height) {
                this.$message.error('图片必须是正方形！')
                reject()
              }
              resolve()
            }
            image.src = event.target.result
          }
          reader.readAsDataURL(file)
        })
      },

      /** 上传logo成功以后*/
      uploadSuccessLogo(response) {
        this.fileList_logo.shift()
        this.fileList_logo.push(response)
        this.shopDataForm.shop_logo = response.url
      },
      /** 图片移除之后 */
      delGiftImg() {
        this.fileList = []
        this.shopDataForm.shop_logo = ''
      }
    }
  }
</script>

<style lang="scss" type="text/scss" scoped>
  .bg-settings {
    background: #fff;
    border: 1px solid #FAFAFA;
    margin: 15px;
    padding: 10px;
  }
  /deep/ .el-form-item--medium .el-form-item__content, .el-form-item--medium .el-form-item__label {
    line-height: 24px;
  }
  /deep/ .upload-demo {
    width: 80%;
  }
  .QQ-tip {
    font-size: 13px;
    color: #796a6a;
  }
</style>
